

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        """
        地址：https://leetcode-cn.com/problems/add-two-numbers/

        :param l1:
        :param l2:
        :return:
        """
        head = tail = None
        carry = 0  # 进位
        while l1 or l2:
            val1 = l1.val if l1 else 0
            val2 = l2.val if l2 else 0
            sum = val1 + val2 + carry
            if not head:
                head = tail = ListNode(sum % 10)
            else:
                tail.next = ListNode(sum % 10)
                tail = tail.next
            carry = sum // 10
            l1 = l1.next if l1 else None
            l2 = l2.next if l2 else None
        if carry > 0:
            tail.next = ListNode(carry)
        return head


def print_list(ret: ListNode):
    collect = []
    while ret:
        collect.append(ret.val)
        ret = ret.next
    print(collect)


if __name__ == '__main__':
    solution = Solution()
    print_list(solution.addTwoNumbers(ListNode(2, ListNode(4, ListNode(3))), ListNode(5, ListNode(6, ListNode(4)))))
    print_list(solution.addTwoNumbers(ListNode(), ListNode()))
    print_list(solution.addTwoNumbers(
        ListNode(9, ListNode(9, ListNode(9, ListNode(9, ListNode(9, ListNode(9, ListNode(9))))))),
        ListNode(9, ListNode(9, ListNode(9, ListNode(9))))))
